package com.dc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dc.common.ResponseResultVO;
import com.dc.entity.*;
import com.dc.entity.ro.SysRoleRO;
import com.dc.entity.ro.SysRoleResourceRO;
import com.dc.exceptions.BizException;
import com.dc.mapper.*;
import com.dc.service.SysResourceService;
import com.dc.service.SysRoleResourceService;
import com.dc.service.SysRoleService;
import com.dc.util.SnowflakeIdWorker;
import com.dc.util.StringUtils;
import com.dc.vo.SysRoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统角色接口实现
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {


    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysResourceMapper sysResourceMapper;

    @Resource
    private SysRoleResourceMapper sysRoleResourceMapper;

    @Resource
    private SysRoleResourceService sysRoleResourceService;

    @Resource
    private SysResourceService sysResourceService;

    @Resource
    private SysUserMapper userMapper;


    @Override
    public ResponseResultVO insert(SysRoleRO sysRoleRO) {
        if (StrUtil.isBlank(sysRoleRO.getRoleName())) {
            return ResponseResultVO.failResult("角色名称不能为空");
        }

        List<SysRole> roleDTOS = sysRoleMapper.selectList(new QueryWrapper<SysRole>().eq("role_name", sysRoleRO.getRoleName()));
        if (!CollectionUtils.isEmpty(roleDTOS)) {
            throw new BizException("角色名有重复");
        }

        if (CollectionUtils.isEmpty(sysRoleRO.getResourceIds())) {
            return ResponseResultVO.failResult("请勾选权限菜单");
        }

        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleRO, sysRole);
        sysRole.setId(SnowflakeIdWorker.generateId());
        sysRoleMapper.insert(sysRole);

        // 2.添加角色权限菜单
        List<SysRoleResource> list = new ArrayList<>();
        for (Long ids : sysRoleRO.getResourceIds()) {
            SysRoleResource sysRoleResource = new SysRoleResource();
            sysRoleResource.setId(SnowflakeIdWorker.generateId());
            sysRoleResource.setRoleId(sysRole.getId());
            sysRoleResource.setResourceId(ids);
            list.add(sysRoleResource);
        }
        sysRoleResourceService.saveBatch(list);

        return ResponseResultVO.successResult("成功");
    }

    @Override
    @Transactional
    public ResponseResultVO update(SysRoleRO sysRoleRO) {
        if (null == sysRoleRO.getId()) {
            return ResponseResultVO.failResult("id不能为空");
        }
        LambdaQueryWrapper<SysRole> queryWrapper = new QueryWrapper<SysRole>().lambda();
        if (StringUtils.isNotBlank(sysRoleRO.getRoleName())) {
            queryWrapper.eq(SysRole::getRoleName, sysRoleRO.getRoleName());
            queryWrapper.ne(SysRole::getId, sysRoleRO.getId());
            SysRole oldSysRole = sysRoleMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(oldSysRole)) {
                return ResponseResultVO.failResult("角色名称重复");
            }
        }
        SysRole sysRole = new SysRole();
        sysRole.setId(sysRoleRO.getId());
        if (StrUtil.isNotBlank(sysRoleRO.getRoleName())) {
            sysRole.setRoleName(sysRoleRO.getRoleName());
        }
        if (StrUtil.isNotBlank(sysRoleRO.getDescription())) {
            sysRole.setDescription(sysRoleRO.getDescription());
        }
        if (null != sysRoleRO.getIsEnable()) {
            sysRole.setIsEnable(sysRoleRO.getIsEnable());
        }
        int num = sysRoleMapper.updateById(sysRole);

        if (CollectionUtils.isEmpty(sysRoleRO.getResourceIds())) {
            return ResponseResultVO.failResult("请勾选权限菜单");
        }
        // 1.删除角色所有的权限菜单
        QueryWrapper<SysRoleResource> resourceQueryWrapper = new QueryWrapper<>();
        resourceQueryWrapper.eq("role_id", sysRoleRO.getId());
        sysRoleResourceMapper.delete(resourceQueryWrapper);

        // 2.添加角色权限菜单
        List<SysRoleResource> list = new ArrayList<>();
        for (Long ids : sysRoleRO.getResourceIds()) {
            SysRoleResource sysRoleResource = new SysRoleResource();
            sysRoleResource.setId(SnowflakeIdWorker.generateId());
            sysRoleResource.setRoleId(sysRoleRO.getId());
            sysRoleResource.setResourceId(ids);
            list.add(sysRoleResource);
        }
        sysRoleResourceService.saveBatch(list);

        return ResponseResultVO.updateResult(num);
    }

    @Override
    public ResponseResultVO delete(String id) {
        List<SysUserRole> sysUserRoles = userRoleMapper.selectList(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, id));
        if (!CollectionUtils.isEmpty(sysUserRoles)) {
            return ResponseResultVO.failResult("当前角色已绑定用户,不允许删除!");
        }
        int num = this.sysRoleMapper.deleteById(id);
        if (num <= 0) {
            return ResponseResultVO.successResult("失败");
        }

        return ResponseResultVO.successResult("成功");
    }

    @Override
    public ResponseResultVO selectList(SysRoleRO sysRoleRO) {
        Page page = new Page<Map<String, Object>>(sysRoleRO.getCurrentPage(), sysRoleRO.getPageSize());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(sysRoleRO.getRoleName())) {
            queryWrapper.like("role_name", sysRoleRO.getRoleName());
        }
        if (StrUtil.isNotBlank(sysRoleRO.getDescription())) {
            queryWrapper.eq("description", sysRoleRO.getRoleName());
        }
        if (StringUtils.isNotBlank(sysRoleRO.getOrderByColumn())) {
            queryWrapper.orderBy(true, "asc".equalsIgnoreCase(sysRoleRO.getIsAsc()) ? true : false, StringUtils.toLine(sysRoleRO.getOrderByColumn()));
        }
        return ResponseResultVO.resultList(sysRoleMapper.selectPage(page, queryWrapper), sysRoleRO);
    }

    @Override
    public ResponseResultVO selectRoleList() {
        return ResponseResultVO.successResult(sysRoleMapper.selectList(new QueryWrapper<SysRole>().lambda().eq(SysRole::getIsEnable, 0)));
    }

    @Override
    public ResponseResultVO updateEnable(SysRoleResourceRO ro) {
        if (ro.getId() == null) {
            return ResponseResultVO.failResult("角色id不能为空");
        }
        SysRole sysRole = new SysRole();
        sysRole.setId(ro.getId());
        sysRole.setIsEnable(ro.getIsEnable());
        return ResponseResultVO.updateResult(sysRoleMapper.updateById(sysRole));
    }

    /**
     * 查询角色菜单信息
     *
     * @param id 角色id
     * @return
     */
    @Override
    public ResponseResultVO selectSysRoleResourceList(String id) {

        if (StrUtil.isBlank(id)) {
            return ResponseResultVO.failResult("角色id不能为空");
        }

        QueryWrapper<SysRoleResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        List<SysRoleResource> sysRoleResources = sysRoleResourceMapper.selectList(queryWrapper);

        List<Long> res = new ArrayList<>();
        for (SysRoleResource sysRoleResource : sysRoleResources) {
            res.add(sysRoleResource.getResourceId());
        }

        QueryWrapper<SysResource> sysResourceDTOQueryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(res)) {
            sysResourceDTOQueryWrapper.in("id", res);
        }
        List<SysResource> sysResources = sysResourceMapper.selectList(sysResourceDTOQueryWrapper);
        Map<Long, SysResource> map = new HashMap<>();
        for (SysResource sysResource : sysResources) {
            map.put(sysResource.getId(), sysResource);
        }

        //查询所有的菜单列表
        List<SysResource> resourceDTOS = sysResourceMapper.selectList(new QueryWrapper<>());
        for (SysResource sysResource : resourceDTOS) {
            if (map.containsKey(sysResource.getId())) {
                sysResource.setSelect(true);
            } else {
                sysResource.setSelect(false);
            }
        }

        return ResponseResultVO.successResult(sysResourceService.listToTreeList(resourceDTOS));

    }

    @Override
    public ResponseResultVO selectRoleById(String id) {
        SysRole sysRole = sysRoleMapper.selectById(id);
        SysRoleVO sysRoleVO = new SysRoleVO();
        BeanUtils.copyProperties(sysRole, sysRoleVO);
        return ResponseResultVO.successResult(sysRoleVO);
    }

    @Override
    public ResponseResultVO selectUserByRole(String id) {
        ResponseResultVO.checkParameterIsNotNull(id, "id不能为空");
        List<SysUserRole> sysUserRoles = userRoleMapper.selectList(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, id));
        List<SysUser> sysUsers = new ArrayList<>();
        if (!CollectionUtils.isEmpty(sysUserRoles)) {
            sysUsers = userMapper.selectList(new QueryWrapper<SysUser>().lambda().eq(SysUser::getId, sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList())));
        }
        return ResponseResultVO.successResult(sysUsers);
    }


}
